/**
 * 
 */
package jmind.core.captcha;

import java.util.Properties;
import java.util.Random;

import jmind.base.util.RandUtil;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.kaptcha.text.TextProducer;
import com.google.code.kaptcha.util.Config;
import com.google.code.kaptcha.util.Configurable;

/**
 * 中文验证码生成器
 * @author wbxie
 * 2013-7-23
 */
public class ChineseTextCreator extends Configurable implements TextProducer {

    private static final Logger log = LoggerFactory.getLogger(ChineseTextCreator.class);

    private final String outputEncode = "UTF-8";

    private static String[] kaptchaIdioms = null;

    @Override
    public String getText() {
        try {
            String result = kaptchaIdioms[RandUtil.nextInt(kaptchaIdioms.length)].trim();
            while (StringUtils.isBlank(result) || result.length() != 4) {
                result = kaptchaIdioms[RandUtil.nextInt(kaptchaIdioms.length)].trim();
            }
            return result;
        } catch (Exception e) {
            log.error("generate random idiom error, so, generate four random chinese character", e);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < 4; i++) {
                sb.append(getChineseCharacter(RandUtil.getRandom()));
            }
            return sb.toString();
        }
        //        final StringBuilder result = new StringBuilder();
        //        for (int i = 0; i < getConfig().getTextProducerCharLength(); i++) {
        //            final String character = String.valueOf(chars[random.nextInt(chars.length)]);
        //            result.append(character);
        //        }
        //        return result.toString();
    }

    @Override
    public void setConfig(final Config config) {
        super.setConfig(config);
        if (kaptchaIdioms == null || kaptchaIdioms.length == 0) {
            Properties properties = new Properties();
            try {
                properties.load(ChineseTextCreator.class.getClassLoader().getResourceAsStream(
                        "kaptcha-idiom.properties"));
                String idioms = properties.getProperty("dictionary");
                kaptchaIdioms = idioms.split(",");
            } catch (Exception e) {
                log.error("kaptcha init error", e);
            }
        }
    }

    private String getChineseCharacter(final Random random) {
        final byte high = new Integer(176 + Math.abs(random.nextInt(39))).byteValue();
        final byte low = new Integer(161 + Math.abs(random.nextInt(93))).byteValue();

        final byte[] bytes = new byte[] { high, low };

        String result = "错";
        try {
            result = new String(new String(bytes, "GB2312").getBytes(outputEncode), outputEncode);

        } catch (final Exception e) {
            log.warn("GB2312 or " + outputEncode + " not supported!", e);
        }
        return result;
    }
}
